//
//  YXCalendarView.m
//  CalendarTest
//
//  Created by 杨潇 on 14-4-14.
//  Copyright (c) 2014年 yx. All rights reserved.
//

#import "YXCalendarView.h"

@implementation YXCalendarView
@synthesize dateStrBlock = _dateStrBlock;
- (void)dealloc
{
    if (_dateStrBlock) {
        _dateStrBlock = nil;
    }
    _nowYM = nil;
    if (_touchBtn) {
        _touchBtn = nil;
    }
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame withBlock:(DateStr)block
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dateStrBlock = block;
        // Initialization code
        self.backgroundColor = [UIColor whiteColor];
        
        NSArray * weekArr = [NSArray arrayWithObjects:@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"周日", nil];
        float w = frame.size.width/7;
        float h = 30;
        NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
        [formatter setDateFormat:@"yyyy-MM"];
        
        NSString * yearBtnTitle;
        for (int i = 0; i < 2; i ++) {
            UIButton * yearUpBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            yearUpBtn.tag = 100 + i;
            yearUpBtn.frame = CGRectMake(20 + (40*3+120)*i, 0, 40, h);
            yearUpBtn.backgroundColor = [UIColor redColor];
            if (i == 0) {
                yearBtnTitle = @"上年";
            }else{
                yearBtnTitle = @"下年";
            }
            [yearUpBtn setTitle:yearBtnTitle forState:UIControlStateNormal];
            [yearUpBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:yearUpBtn];
        }
        
        NSString * monthBtnTitle;
        for (int i = 0; i < 2; i ++) {
            UIButton * yearUpBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            yearUpBtn.tag = 102 + i;
            yearUpBtn.frame = CGRectMake(70 + (40 + 100)*i, 0, 40, h);
            yearUpBtn.backgroundColor = [UIColor redColor];
            if (i == 0) {
                monthBtnTitle = @"上月";
            }else{
                monthBtnTitle = @"下月";
            }
            [yearUpBtn setTitle:monthBtnTitle forState:UIControlStateNormal];
            [yearUpBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:yearUpBtn];
        }
        
        _dateLab = [[[UILabel alloc] init] autorelease];
        _dateLab.text = [formatter stringFromDate:[NSDate date]];
        _dateLab.textAlignment = NSTextAlignmentCenter;
        _dateLab.frame = CGRectMake(110, 0, 100, h);
        _dateLab.textColor = [UIColor blackColor];
        _dateLab.layer.borderColor = [UIColor grayColor].CGColor;
        _dateLab.layer.borderWidth = .5;
        [self addSubview:_dateLab];
        _nowYM = [[formatter stringFromDate:[NSDate date]] copy];
        
        int x = 0;
        int y = 0;
        for (int i = 0; i < 7; i ++) {

            UILabel * weekLabel = [[[UILabel alloc] init] autorelease];
            weekLabel.textAlignment = NSTextAlignmentCenter;
            weekLabel.frame = CGRectMake(w*i, h, w, 20);
            weekLabel.text = [weekArr objectAtIndex:i];
            weekLabel.textColor = [UIColor blackColor];
            weekLabel.layer.borderColor = [UIColor grayColor].CGColor;
            weekLabel.layer.borderWidth = .5;
            [self addSubview:weekLabel];
            if (x >= 7) {
                y ++;
                x = 0;
            }
            x ++;
        }
        [self createDayBtnWithDate:[NSDate date]];
    }
    return self;
}

#pragma mark - btnClick
- (void)btnClick:(UIButton *)btn
{
    NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    if (btn == _nowBtn) {
        if ([btn.titleLabel.text intValue]<10) {
            self.dateStrBlock([NSString stringWithFormat:@"%@-0%@",_dateLab.text,btn.titleLabel.text]);
        }else{
            self.dateStrBlock([NSString stringWithFormat:@"%@-%@",_dateLab.text,btn.titleLabel.text]);
        }
    }
    if (1<= btn.tag && btn.tag <= 31 && btn != _nowBtn) {
        if ([btn.titleLabel.text intValue]<10) {
            self.dateStrBlock([NSString stringWithFormat:@"%@-0%@",_dateLab.text,btn.titleLabel.text]);
        }else{
            self.dateStrBlock([NSString stringWithFormat:@"%@-%@",_dateLab.text,btn.titleLabel.text]);
        }
        if (_touchBtn) {
            [_touchBtn setBackgroundColor:[UIColor clearColor]];
            _touchBtn = nil;
        }
        [btn setBackgroundColor:[UIColor greenColor]];
        _touchBtn = [btn retain];
        return;
    }
    switch (btn.tag) {
        case 100:
        {
            [self upYear];
            if ([_nowYM isEqualToString:_dateLab.text]) {
                [self createDayBtnWithDate:[NSDate date]];
            }else{
                [self createDayBtnWithDate:[formatter dateFromString:[NSString stringWithFormat:@"%@-01",_dateLab.text]]];
            }
            
        }
            break;
        case 101:
        {
            [self downYear];
            if ([_nowYM isEqualToString:_dateLab.text]) {
                [self createDayBtnWithDate:[NSDate date]];
            }else{
                [self createDayBtnWithDate:[formatter dateFromString:[NSString stringWithFormat:@"%@-01",_dateLab.text]]];
            }
        }
            break;
        case 102:
        {
            [self upMonth];
            if ([_nowYM isEqualToString:_dateLab.text]) {
                [self createDayBtnWithDate:[NSDate date]];
            }else{
                [self createDayBtnWithDate:[formatter dateFromString:[NSString stringWithFormat:@"%@-01",_dateLab.text]]];
            }
        }
            break;
        case 103:
        {
            [self downMonth];
            if ([_nowYM isEqualToString:_dateLab.text]) {
                [self createDayBtnWithDate:[NSDate date]];
            }else{
                [self createDayBtnWithDate:[formatter dateFromString:[NSString stringWithFormat:@"%@-01",_dateLab.text]]];
            }
        }
            break;
            
        default:
            break;
    }
}

- (void)createDayBtnWithDate:(NSDate *)date
{
    float w = self.frame.size.width/7;
    NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    
    NSString * nowDate = [formatter stringFromDate:date];
    int nowDay = [[[nowDate componentsSeparatedByString:@"-"] objectAtIndex:2] intValue];
    NSString * firstDate = [[nowDate substringToIndex:8] stringByAppendingString:@"01"];
    NSDateComponents * components = [calendar components:NSYearCalendarUnit |NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[formatter dateFromString:firstDate]];
    int startX = [components weekday] - 1;
    if (startX == 0) {
        startX = 7;
    }
    int starty = 0;
    for (int i = 0; i < range.length; i ++) {
        UIButton * dayBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        if (i == (nowDay - 1) && [_dateLab.text isEqualToString:_nowYM]) {
            _nowBtn = dayBtn;
            [dayBtn setBackgroundColor:[UIColor grayColor]];
        }
        [dayBtn setTitle:[NSString stringWithFormat:@"%d",i + 1] forState:UIControlStateNormal];
        dayBtn.frame = CGRectMake(w*(startX-1), w*starty+50, w, w);
        dayBtn.tag = i + 1;
        [dayBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:dayBtn];
        if (startX >= 7) {
            startX = 0;
            starty ++;
        }
        startX ++;
    }
}

- (void)upYear
{
    NSArray * dateArr = [_dateLab.text componentsSeparatedByString:@"-"];
    _dateLab.text = [NSString stringWithFormat:@"%d-%@",[[dateArr objectAtIndex:0] intValue] - 1,[dateArr objectAtIndex:1]];
    [self removeAllBtn];
}

- (void)downYear
{
    NSArray * dateArr = [_dateLab.text componentsSeparatedByString:@"-"];
    _dateLab.text = [NSString stringWithFormat:@"%d-%@",[[dateArr objectAtIndex:0] intValue] + 1,[dateArr objectAtIndex:1]];
    [self removeAllBtn];
}

- (void)upMonth
{
    NSArray * dateArr = [_dateLab.text componentsSeparatedByString:@"-"];
    int month = [[dateArr objectAtIndex:1] intValue] - 1;
    if (month <= 0) {
        month = 12;
        [self upYear];
        dateArr = [_dateLab.text componentsSeparatedByString:@"-"];
    }
    if (month < 10) {
        _dateLab.text = [NSString stringWithFormat:@"%@-0%d",[dateArr objectAtIndex:0],month];
    }else{
        _dateLab.text = [NSString stringWithFormat:@"%@-%d",[dateArr objectAtIndex:0],month];
    }
    
    [self removeAllBtn];
}

- (void)downMonth
{
    NSArray * dateArr = [_dateLab.text componentsSeparatedByString:@"-"];
    int month = [[dateArr objectAtIndex:1] intValue] + 1;
    if (month > 12) {
        month = 1;
        [self downYear];
        dateArr = [_dateLab.text componentsSeparatedByString:@"-"];
    }
    if (month < 10) {
        _dateLab.text = [NSString stringWithFormat:@"%@-0%d",[dateArr objectAtIndex:0],month];
    }else{
        _dateLab.text = [NSString stringWithFormat:@"%@-%d",[dateArr objectAtIndex:0],month];
    }
    [self removeAllBtn];
}

- (void)removeAllBtn
{
    int i = 0;
    while (YES) {
        i ++;
        UIButton * dayBtn = (UIButton *)[self viewWithTag:i];
        if (dayBtn) {
            [dayBtn removeFromSuperview];
        }else{
            break;
        }
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
